package gateway.mgt.api

import com.amihaiemil.camel.YamlSequenceBuilder

class ApiSystemParam implements ApiDefinition.Pluggable {

    static enum Scope {
        Query, Path, Header
    }

    static enum Type {
        String, Integer, Long, Float, Double, Boolean
    }

    static enum SystemVariable {
        OS_Name, OS_Date
    }

    Integer order

    Type type
    Scope scope
    String name
    SystemVariable value

    Date dateCreated
    Date lastUpdated

    static belongsTo = [apiDefinition: ApiDefinition]

    String description

    static constraints = {
        apiDefinition(nullable: false)
        order(nullable: false, min: 1, unique: "apiDefinition")
        type(nullable: false)
        scope(nullable: false)
        name(blank: false)
        value(nullable: false)
        description(nullable: true, maxSize: 200, widget: 'textarea')
        dateCreated()
        lastUpdated()
    }

    static mapping = {
        order column: "_order"
    }

    @Override
    void plug(Map<String, YamlSequenceBuilder> routeBuildElements, final ApiDefinition current) {
        switch (scope) {
            case Scope.Header:
                routeBuildElements.filters = routeBuildElements.filters.add("AddRequestHeader=${name}, ${value}")
                break
            case Scope.Query:
                routeBuildElements.filters = routeBuildElements.filters.add("AddRequestParameter=${name}, ${value}")
                break
            case Scope.Path:
                routeBuildElements.filters = routeBuildElements.filters.add("PrefixPath=/$value")
                break
        }
    }
}
